package com.quectel.cms.controller.village;


import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.dto.VillageFloorDto;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageFloorService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.POIUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-10-18 14:41:35
 */
@RestController
@RequestMapping("villageFloor")
@Tag(name = "VillageFloorController", description = "楼层相关api")
public class VillageFloorController extends BaseController {
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private VillageFloorService villageFloorService;
    @DubboReference
    private VillageRoomService villageRoomService;

    /**
     * 根据楼栋筛选楼层
     */
    @GetMapping("queryByBuildingId")
    @Operation(summary = "根据楼栋筛选楼层")
    public Response<List<VillageFloorDto>> queryByBuildingId(
            @Parameter(description = "楼栋") @RequestParam Long buildingId
    ) {

        return Response.<List<VillageFloorDto>>ok().wrap(villageFloorService.selectByBuildingId(buildingId));
    }

    /**
     * excel导入楼层信息
     */
    @PostMapping("importExcel")
    @RequirePermissions(values = "villageFloor:importExcel")
    @Operation(summary = "excel导入楼层信息")
    @Log(express = "导入楼栋信息")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {
        int totalCount = 0;
        int successCount = 0;
        List<VillageFloorDto> floors = new ArrayList<>();
        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                try {
                    //校验楼栋数据合法性
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);
                    for (Map<Integer, String> map : analysis) {

                        ++totalCount;

                        try {
                            VillageDto villageDto = villageService.selectByName(SessionHolder.getSysUser().getTenantId(), map.get(0));
                            if (villageDto == null) {
                                continue;
                            }
                            VillageBuildingDto villageBuildingDto = villageBuildingService.selectByName(villageDto.getId(), map.get(1));
                            if (villageBuildingDto == null) {
                                continue;
                            }

                            VillageFloorDto villageFloorDto = new VillageFloorDto();
                            villageFloorDto.setVillageId(villageDto.getId());
                            villageFloorDto.setBuildingId(villageBuildingDto.getId());
                            villageFloorDto.setFloorNo(StringUtils.isNotBlank(map.get(2)) ? Integer.valueOf(map.get(2)) : null);
                            villageFloorDto.setName(map.get(3));
                            fillSaveCommonData(villageFloorDto);
                            floors.add(villageFloorDto);
                        } catch (Exception e) {
                            logger.error("表格中有错误数据", e);
                        }
                    }
                } catch (Exception e) {
                    logger.error("解析楼层信息出错");
                }
            }
        }
        for (VillageFloorDto villageFloorDto : floors) {
            VillageFloorDto dbValue = villageFloorService.selectByFloorNo(villageFloorDto.getBuildingId(), villageFloorDto.getFloorNo());
            if (dbValue != null) {
            } else {
                try {
                    villageFloorService.save(villageFloorDto);
                    successCount++;
                } catch (Exception e) {
                    logger.error("保存导入数据出错", e);
                }

            }

        }
        return Response.error("导入数据完成，总条数:" + totalCount + "成功条数:" + successCount);
    }

    /**
     * 导出楼层信息为excel文件
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "villageBuilding:exportExcel")
    @Log(express = "导出楼层信息")
    @Operation(summary = "导出楼层信息为excel文件")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);

        List<VillageFloorDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<VillageFloorDto> list = villageFloorService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"所属小区", "所属楼栋", "层高", "楼层名称"};
        List<String[]> dataList = new ArrayList<>();
        for (VillageFloorDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = data.getBuildingName();
            item[2] = data.getFloorNo() + "";
            item[3] = data.getName();
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "楼层信息", headers, dataList, "楼层信息");
    }

    /**
     * 根据参数小区楼层分页查询列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "villageFloor:list")
    @Operation(summary = "根据参数小区楼层分页查询列表")
    public Response<Page<VillageFloorDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = villageFloorService.queryTotal(request.getParams());

        List<VillageFloorDto> list = null;
        if (total > 0) {
            list = villageFloorService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<VillageFloorDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<VillageFloorDto>>ok().wrap(page);
    }


    /**
     * 根据id查询小区楼层信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "villageFloor:info")
    @Operation(summary = "根据id查询小区楼层信息")
    public Response<VillageFloorDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (villageFloorService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        VillageFloorDto villageFloorDto = villageFloorService.selectById(id);

        return Response.<VillageFloorDto>ok().wrap(villageFloorDto);
    }

    /**
     * 保存小区楼层信息
     */
    @PostMapping("save")
    @RequirePermissions(values = "villageFloor:edit")
    @Operation(summary = "保存小区楼层信息")
    @Log(express = "保存楼层")
    public Response<Object> save(@RequestBody @Validated VillageFloorDto villageFloorDto) {

        VillageFloorDto dbValue = villageFloorService.selectByFloorNo(villageFloorDto.getBuildingId(), villageFloorDto.getFloorNo());
        if (dbValue != null) {
            return Response.error("该楼层已经存在");
        }
        //填充基础数据
        fillSaveCommonData(villageFloorDto);

        villageFloorService.save(villageFloorDto);

        return Response.ok();
    }

    /**
     * 修改小区楼层记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "villageFloor:edit")
    @Operation(summary = "修改小区楼层记录")
    @Log(express = "编辑楼层")
    public Response<Object> update(@RequestBody @Validated VillageFloorDto villageFloorDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(villageFloorDto.getId()));
        if (villageFloorService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        VillageFloorDto dbValue = villageFloorService.selectByFloorNo(villageFloorDto.getBuildingId(), villageFloorDto.getFloorNo());
        if (dbValue != null && !Objects.equals(dbValue.getId(), villageFloorDto.getId())) {
            return Response.error("该楼层已经存在");
        }
        //填充基础数据
        fillEditCommonData(villageFloorDto);

        villageFloorService.updateById(villageFloorDto);

        return Response.ok();
    }

    /**
     * 批量删除小区楼层记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "villageFloor:delete")
    @Operation(summary = "批量删除小区楼层记录")
    @Log(express = "删除楼层")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (villageFloorService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
            List<VillageRoomDto> rooms = villageRoomService.selectByFloorId(id);
            if (rooms != null && rooms.size() > 0) {
                return Response.error("该楼层下存在房间,不允许删除");
            }
        }


        villageFloorService.deleteBatch(ids);

        return Response.ok();
    }
}
